<template>
  <div class="recorder">
    <button @click="startRecording" :disabled="isRecording">开始录音</button>
    <button @click="stopRecording" :disabled="!isRecording">停止录音</button>
    <button @click="playRecording" :disabled="!recordedBlob">播放录音</button>
    <button @click="playAudio">转换为语音并获取时长</button>
    {{this.recordedUrl}}
  </div>
</template>

<script>
export default {
  data () {
    return {
      isRecording: false,
      mediaRecorder: null,
      chunks: [],
      recordedBlob: null,
      recordedUrl: 'blob:https://oem-test.seventeen.tech/29d5761f- 9a3f-494b-8ab0-0d08170d2ed3',
    };
  },
  methods: {
    convertBinaryToString (binaryData) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();

        reader.onloadend = () => {
          const result = reader.result;
          resolve(result);
        };

        reader.onerror = () => {
          reject(new Error('无法将二进制数据转换为字符串。'));
        };

        reader.readAsDataURL(binaryData);
      });
    },
    convertToSpeech () {
      const recordedUrl = 'blob:https://oem-test.seventeen.tech/29d5761f-9a3f-494b-8ab0-0d08170d2ed3';
      const audioCtx = new (window.AudioContext || window.webkitAudioContext)();

      fetch(recordedUrl)
        .then(response => response.arrayBuffer())
        .then(arrayBuffer => {
          return audioCtx.decodeAudioData(arrayBuffer);
        })
        .then(decodedBuffer => {
          console.log("Decoded buffer:", decodedBuffer);
          // 解码完成后的处理逻辑
        })
        .catch(error => {
          console.error('Error converting audio data:', error);
        });
    },
    startRecording () {
      navigator.mediaDevices.getUserMedia({
        audio: true
      })
        .then((stream) => {
          this.isRecording = true;
          this.chunks = [];
          this.mediaRecorder = new MediaRecorder(stream);
          this.mediaRecorder.addEventListener('dataavailable', (event) => {
            this.chunks.push(event.data);
            // this.convertBinaryToString(event.data)
            //   .then(strData => {
            //     console.log('转换后的字符串数据:', strData);
            //     // 在这里可以将字符串数据发送到服务器或进行其他处理
            //   })
            //   .catch(error => {
            //     console.error('转换失败:', error);
            //   });
            console.log('event.data', event.data)
          });
          this.mediaRecorder.start();
        })
        .catch((error) => {
          console.error('无法访问麦克风:', error);
        });
    },
    stopRecording () {
      if (this.mediaRecorder && this.isRecording) {
        this.mediaRecorder.addEventListener('stop', () => {
          this.isRecording = false;

          const blob = new Blob(this.chunks, {
            type: 'audio/mp3'
          });
          this.recordedBlob = blob;
          this.recordedUrl = URL.createObjectURL(blob);
          console.log('录音已保存：', this.recordedUrl);
        });
        this.mediaRecorder.stop();
      }
    },
    playRecording () {
      if (this.recordedUrl) {
        const audio = new Audio(this.recordedUrl);
        audio.play();
      }
    },
    playAudio (audioData) {
      const audioContext = new (window.AudioContext || window.webkitAudioContext)();
      const sourceNode = audioContext.createBufferSource();

      audioContext.decodeAudioData(audioData, (audioBuffer) => {
        sourceNode.buffer = audioBuffer;
        sourceNode.connect(audioContext.destination);
        sourceNode.start();
      }, (error) => {
        console.error('Error decoding audio data:', error);
      });
    }
  },
};
</script>